<template>
  <div>
    <TopFilter :list="topFilterList" :cols="3" :labelWidth="100" :collapse="false" @onCollapse="collapseHandle" @filterChange="handleFilterChange" />
    <FilterTable
      ref="mainTable"
      :fetchapi="fetchapi"
      :params="fetchParams"
      :columns="tableColumns"
      columnsRef="partPartPurchasePurchaseOrderIndex"
      :datakey="'rows'"
      selectionType="single"
      :onRowSelectChange="handleRowSelectChange"
      :onColumnsChange="columns => (this.tableColumns = columns)"
      :isExportExcel="true"
      :onCalcExportData="exportFun"
      exportFileName="配件采购订单.xlsx"
    >
      <template slot="controls">
        <el-button size="small" type="primary" icon="el-icon-plus" @click="createNewOrder">新建</el-button>
        <AjaxButton size="small" type="primary" :click="handleOrderUpload">订单上传</AjaxButton>
        <AjaxButton size="small" type="primary" :click="handleDealOverdueOrder">处理过期订单</AjaxButton>
        <el-button size="small" type="primary" @click="potabPageVisible = true">Potal查询</el-button>
        <el-button size="small" type="primary" @click="changeOrderExcutiveConditionVisible(true)">订单执行情况</el-button>
        <el-button size="small" type="primary" @click="handleCheckR3Log">查看R3日志</el-button>
        <el-button size="small" type="primary" @click="etkaReceivePartVisible = true">ETKA接受配件</el-button>
      </template>
    </FilterTable>

    <!-- 供应商选择 -->
    <BaseDialog :visible.sync="showSupplierSelecter" title="供应商查询" destroyOnClose :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
      <provideSearchHelper @close="showSupplierSelecter = false" @onConfirm="handleDealerSelectConfirm" />
    </BaseDialog>
    <!-- 新建采购订单一级抽屉 -->
    <Drawer
      :visible.sync="showCreateMainDrawer"
      :title="drawerText"
      destroyOnClose
      width="75%"
      :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }"
      @close="handleDrawerClose"
    >
      <createOrderMain
        :orderNo="editOrderNo"
        :addMode="drawerIsAdd"
        :partList="partList"
        :assignOrderType="createOrderType"
        @drawerChange="handleCreateDrawerChange"
        @resetTableData="handleResetTableData"
      />
    </Drawer>
    <!-- 查询订单执行情况 -->
    <Drawer :visible.sync="showOrderExcutiveCondition" title="订单执行情况查询" destroyOnClose :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
      <OrderExecutiveCondition :showClose="true" @close="showOrderExcutiveCondition = false" />
    </Drawer>
    <!-- 查看r3日志 -->
    <BaseDialog :visible.sync="quertR3DialogVisible" title="查看r3日志" destroyOnClose :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
      <queryR3Dialog :billNo="checkR3LogBillNo" @close="quertR3DialogVisible = false" />
    </BaseDialog>
    <!-- etka接收配件 -->
    <BaseDialog :visible.sync="etkaReceivePartVisible" title="ETKA接收配件" destroyOnClose :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
      <etkaReceivePart @close="etkaReceivePartVisible = false" @onEtkaPartAddToOldOrder="handleEtkaPartAddToOldOrder" @onEtkaPartCreateNewOrder="handleEtkaPartCreateNewOrder" />
    </BaseDialog>
    <!-- 订单详情页 -->
    <BaseDialog :visible.sync="orderDetailVisible" title="订单详情" destroyOnClose :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
      <orderDetail :orderId="checkedOrderId" @close="orderDetailVisible = false" />
    </BaseDialog>
  </div>
</template>

<script>
import { queryOrderList, queryAllOrderTypeInfo, uploadOrder, dealOverdueOrder, lockOrderForEdit, unlockOrderForEdit, queryOrderIsLocked } from '@/api/part/partPurchase/purchaseOrder';

import { messageAction, notifyAction, formatdate } from '@/utils';
import { dictionary } from '@/utils/dictMixin';
import { authority } from '@/utils/authMixin';
import { getUserId } from '@/assets/js/auth';
import { getDealerUser } from '@/api/part/partInventory/partInventory/index.js';

import provideSearchHelper from './provideSearchHelper';
import CreateOrderMain from './CreateOrderMain';
import orderDetail from './orderDetail';
// import OrderExecutiveCondition from './main/OrderExecutiveCondition';
import OrderExecutiveCondition from '@/pages/part/report/orderExecution';
import queryR3Dialog from './main/queryR3Dialog';
import etkaReceivePart from './main/etkaReceivePart';
import moment from 'moment';

export default {
  name: 'partPurchaseOrderQuery',
  components: {
    provideSearchHelper,
    CreateOrderMain,
    OrderExecutiveCondition,
    queryR3Dialog,
    etkaReceivePart,
    orderDetail
  },
  mixins: [dictionary, authority],
  data() {
    return {
      topFilterList: this.createTopFilterList(),
      tableColumns: this.createTableColumns(),
      showCreateMainDrawer: false,
      showSupplierSelecter: false, // 是否显示供应商选择
      showOrderExcutiveCondition: false, // 是否显示订单执行状况
      quertR3DialogVisible: false, // 是否显示查看r3日志
      etkaReceivePartVisible: false, // 是否显示etka接收配件
      orderDetailVisible: false, // 是否显示订单详情
      potabPageVisible: false, // 是否显示potal弹窗
      fetchapi: queryOrderList,
      fetchParams: { xhrAbort: true },
      drawerText: '新建订单',
      drawerIsAdd: false, // 订单抽屉是否是编辑状态
      checkedOrderId: '', // 查看详情的订单id
      orderTypeList: [], // 订单类型列表(回显用)
      selectedOrderList: [], // 选中的订单列表
      partList: [], // 传递给编辑\新建订单的配件列表
      editOrderNo: '', // 传递给订单添加\编辑组件的订单No
      editOrderItemId: '', // 编辑的订单主键（解锁用）
      createOrderType: 1, // 传递给订单创建的指定订单类型(etka接收配件fib类型订单)
      checkR3LogBillNo: '', // 查看r3日志的订单编号
      selectedCustomer: {
        // 选中的供应商信息
        customerName: '一汽大众汽车有限公司',
        customerCode: 'FAW-VW'
      },
      userInfoData: {} // 用户列表信息
    };
  },
  computed: {
    ptype() {
      return this.$route.meta.ptype;
    }
  },
  created() {
    this.queryAllOrderTypeInfoList();
    this.setSearchDateDefaultValue();
    this.getDealerUser();
  },
  methods: {
    exportFun(row) {
      console.log(this.tableColumns);
      for (const key in row) {
        switch (key) {
          case 'operation':
            row[key] = row.index;
            break;
          case 'vOrderStatus':
            row[key] = this.createDictText(row.vOrderStatus, 8133);
            break;
          case 'vBillStatus':
            row[key] = this.createDictText(row.vBillStatus, 8100);
            break;
          case 'cUpload':
            if (row.cUpload == true) {
              row[key] = '已上传';
            } else {
              row[key] = '未上传';
            }
            break;
          case 'cConfirm':
            if (row.cConfirm == true) {
              row[key] = '已锁定';
            } else {
              row[key] = '未锁定';
            }
            break;
          case 'vTransport':
            row[key] = this.createDictText(row.vTransport, 8114);
            break;
          case 'dCreate':
            row[key] = row[key] ? moment(row[key]).format('YYYY-MM-DD') : '';
            break;
          case 'dUpLoad':
            row[key] = row[key] ? moment(row[key]).format('YYYY-MM-DD') : '';
            break;
          case 'dSubmit':
            row[key] = row[key] ? moment(row[key]).format('YYYY-MM-DD') : '';
            break;
          default:
            break;
        }
      }
    },
    createTopFilterList() {
      return [
        // {
        //   type: 'SELECT',
        //   label: '网络',
        //   fieldName: 'a1',
        //   placeholder: '请选择...',
        //   itemList: [{ text: '00', value: '1' }, { text: '11', value: '2' }],
        //   rules: [{ required: true, message: '请选择网络', trigger: 'change' }]
        // },
        {
          type: 'INPUT',
          label: '采购订单编号',
          fieldName: 'orderNo',
          placeholder: '请输入...'
        },
        {
          type: 'INPUT',
          label: '供应商',
          fieldName: 'vSupplyId',
          placeholder: '请选择...',
          initialValue: '一汽大众汽车有限公司',
          noResetable: true,
          unitRender: () => {
            return <el-button slot="append" icon="el-icon-search" onClick={this.showProvideSearchHelper}></el-button>;
          },
          readonly: true
        },
        {
          type: 'RANGE_DATE',
          fieldName: 'startDCreate|endDCreate',
          label: '制单日期',
          initialValue: [],
          dateType: 'daterange'
        },
        {
          type: 'SELECT',
          label: '订单状态',
          fieldName: 'vOrderStatus',
          placeholder: '请选择...',
          initialValue: 81331001,
          itemList: this.createDictList(8133)
        }
      ];
    },
    createTableColumns() {
      return [
        {
          title: '操作',
          dataIndex: 'column-action',
          fixed: 'left',
          render: params => {
            return (
              <div>
                <el-button type="text" disabled={!!params.row.cUpload} size="mini" onClick={() => this.handleEdit(params.row)}>
                  编辑
                </el-button>
                <el-divider direction="vertical"></el-divider>
                <el-button type="text" size="mini" onClick={() => this.handleCheckDetail(params.row)}>
                  详情
                </el-button>
              </div>
            );
          }
        },
        {
          title: '订单编号',
          dataIndex: 'orderNo',
          filter: true,
          sorter: true,
          filterType: 'input'
        },
        {
          title: '订单类型',
          dataIndex: 'originalOrderType',
          render: params => {
            return <span>{this.orderTypeList[params.row.originalOrderType]}</span>;
          },
          filter: true,
          sorter: true,
          filterType: 'checkbox',
          filterItems: []
        },
        {
          title: '订单状态',
          dataIndex: 'vOrderStatus',
          render: params => {
            return <span>{this.createDictText(params.row.vOrderStatus, 8133)}</span>;
          },
          filter: true,
          sorter: true,
          filterType: 'checkbox',
          filterItems: this.createDictList(8133)
        },
        {
          title: '单据状态',
          dataIndex: 'vBillStatus',
          render: params => {
            return <span>{this.createDictText(params.row.vBillStatus, 8100)}</span>;
          },
          filter: true,
          sorter: true,
          filterType: 'checkbox',
          filterItems: this.createDictList(8100)
        },
        {
          title: '提交日期',
          dataIndex: 'dSubmit',
          dateFormat: 'yyyy-MM-dd',
          filter: true,
          sorter: true,
          filterType: 'date-range'
        },
        {
          title: '上传标识',
          dataIndex: 'cUpload',
          align: 'center',
          render: params => {
            return <el-checkbox disabled={true} checked={!!params.row.cUpload}></el-checkbox>;
          },
          filter: true,
          sorter: true,
          filterType: 'checkbox',
          filterItems: [
            { text: '已上传', value: true },
            { text: '未上传', value: 'null' }
          ]
        },
        {
          title: '锁定标识',
          dataIndex: 'cConfirm',
          align: 'center',
          render: params => {
            return <el-checkbox disabled={true} checked={!!params.row.cConfirm}></el-checkbox>;
          },
          filter: true,
          sorter: true,
          filterType: 'checkbox',
          filterItems: [
            { text: '已锁定', value: true },
            { text: '未锁定', value: 'null' }
          ]
        },
        // {
        //   title: '性质',
        //   dataIndex: 'vProperties'
        // },
        {
          title: '运输方式',
          dataIndex: 'vTransport',
          render: params => {
            return <span>{this.createDictText(params.row.vTransport, 8114)}</span>;
          },
          filter: true,
          sorter: true,
          filterType: 'checkbox',
          filterItems: this.createDictList(8114)
        },
        {
          title: '制单日期',
          dataIndex: 'dCreate',
          dateFormat: 'yyyy-MM-dd',
          filter: true,
          sorter: true,
          filterType: 'date-range'
        },
        {
          title: '拒绝原因',
          dataIndex: 'vRejectReason',
          filter: true,
          sorter: true,
          filterType: 'input'
        },
        // {
        //   title: '确认',
        //   dataIndex: 'cConfirm',
        //   filter: true,
        //   filterType: 'input'
        // },
        // {
        //   title: '确认代码',
        //   dataIndex: 'cConfirmId',
        //   filter: true,
        //   filterType: 'input'
        // },
        {
          title: '上传日期',
          dataIndex: 'dUpLoad',
          dateFormat: 'yyyy-MM-dd',
          filter: true,
          sorter: true,
          filterType: 'date-range'
        }
        // {
        //   title: '确认日期',
        //   dataIndex: 'dConfirm',
        //   dateFormat: 'yyyy-MM-dd',
        //   filter: true,
        //   filterType: 'date-range'
        // }
      ];
    },
    collapseHandle() {
      this.$nextTick(() => {
        this.$refs.mainTable.$refs.pageTable.EXECUTE_RESET_HEIGHT();
      });
    },
    // 设置制单日期搜索条件初始值
    setSearchDateDefaultValue() {
      let date = new Date();
      let year = date.getFullYear();
      let month = date.getMonth() + 1;
      this.topFilterList.find(item => item.fieldName == 'startDCreate|endDCreate').initialValue = [formatdate(new Date(year + '/' + month + '/1'), 1), formatdate(date, 1)];
    },
    // 首页点击搜索或者重置
    handleFilterChange(e) {
      console.log(e);
      this.fetchParams.xhrAbort = true;
      this.fetchParams = Object.assign(this.fetchParams, {
        ...e,
        xhrAbort: false,
        startDCreate: e.startDCreate ? e.startDCreate.split(' ')[0] : '',
        endDCreate: e.endDCreate ? e.endDCreate.split(' ')[0] : '',
        vSupplyId: e.vSupplyId ? this.selectedCustomer.customerCode : '',
        ptype: this.ptype || ''
      });
    },
    // table选择变化
    handleRowSelectChange(e) {
      this.selectedOrderList = e;
    },
    // table重新查询
    handleResetTableData() {
      this.fetchParams.xhrAbort = true;
      this.fetchParams.xhrAbort = false;
    },
    // 查询所有订单类型
    async queryAllOrderTypeInfoList() {
      let res = await queryAllOrderTypeInfo();
      let obj = {};
      res.data.map(item => {
        obj[item.partTypeId] = item.partTypeName;
      });
      this.tableColumns.find(item => item.dataIndex == 'originalOrderType').filterItems = res.data.map(item => ({ text: item.partTypeName, value: item.partTypeId + '' }));
      this.tableColumns.find(item => item.dataIndex == 'originalOrderType').editItems = res.data.map(item => ({ text: item.partTypeName, value: item.partTypeId + '' }));
      this.orderTypeList = obj;
    },
    // 切换供应商选择展示
    showProvideSearchHelper() {
      this.showSupplierSelecter = true;
    },
    // 供应商选择点击确定
    handleDealerSelectConfirm(e) {
      this.selectedCustomer = e;
      this.topFilterList.find(item => item.fieldName == 'vSupplyId').initialValue = e.customerName;
    },
    // 点击查看r3日志
    handleCheckR3Log() {
      if (this.selectedOrderList.length) {
        this.checkR3LogBillNo = this.selectedOrderList[0].orderNo;
        this.quertR3DialogVisible = true;
      } else {
        messageAction('请选择需要查看的订单', 'warning');
      }
    },
    // 点击新建订单
    createNewOrder() {
      this.drawerText = '新建订单';
      this.drawerIsAdd = true;
      this.handleCreateDrawerChange(true);
    },
    // 新建弹窗关闭事件
    handleDrawerClose() {
      console.log(this.drawerIsAdd);
      // 弹窗关闭清空编辑数据
      this.partList = [];
      this.editOrderNo = '';
      this.createOrderType = 1;

      if (!this.drawerIsAdd) {
        unlockOrderForEdit(this.editOrderItemId);
      }
    },
    // 修改创建订单抽屉展开收起状态
    handleCreateDrawerChange(val) {
      if (!val) {
        // 添加\编辑弹窗关闭时重置传入添加组件的订单列表
        this.partList = [];
        this.editOrderNo = '';
        this.createOrderType = 1;
      }
      this.showCreateMainDrawer = val;
    },
    // 修改订单执行情况弹框
    changeOrderExcutiveConditionVisible(val) {
      this.showOrderExcutiveCondition = val;
    },
    // 点击编辑按钮
    async handleEdit(e) {
      let loginUserId = getUserId();
      let lockInfo = '';

      // 查询订单是否被锁定
      try {
        lockInfo = (await queryOrderIsLocked(e.itemId)).data;
      } catch (err) {
        console.log('查询订单锁定状态失败', err);
      }

      if (!lockInfo) {
        let lockRes = '';
        try {
          lockRes = await lockOrderForEdit(e.itemId);
        } catch (err) {
          console.log('订单锁定失败', err);
        }
        if (lockRes.resultCode == 200) {
          this.openEditPage(e);
        }
      } else {
        if (lockInfo == loginUserId) {
          this.openEditPage(e);
        } else {
          notifyAction('该订单已被他人锁定，锁定人：' + this.userInfoData[lockInfo] || lockInfo, 'warning');
        }
      }
    },
    // 打开编辑页面
    openEditPage(e) {
      this.editOrderNo = e.orderNo;
      this.editOrderItemId = e.itemId;
      this.drawerIsAdd = false;
      this.drawerText = '订单编辑';
      this.handleCreateDrawerChange(true);
    },
    // 点击查看详情
    handleCheckDetail(e) {
      this.checkedOrderId = e.orderNo;
      this.orderDetailVisible = true;
    },
    // 点击订单上传
    async handleOrderUpload() {
      if (this.selectedOrderList.length) {
        let res = await uploadOrder({
          itemId: this.selectedOrderList[0].itemId
        });
        if (res.resultCode == 200) {
          messageAction('上传成功', 'success');
          this.handleResetTableData();
        }
      } else {
        messageAction('请选择需要上传的订单', 'warning');
      }
    },
    // etka接收配件点击添加现有订单
    handleEtkaPartAddToOldOrder(e) {
      console.log('etka接收配件点击添加现有订单', e);
      this.partList = e.partList;
      this.editOrderNo = e.orderInfo.orderNo;
      this.handleCreateDrawerChange(true);
    },
    // etka接收配件点击新建订单
    handleEtkaPartCreateNewOrder(e) {
      console.log('etka接收配件点击创建新订单', e);
      this.partList = e.partList;
      // this.createOrderType = e.isFib ? 3 : 1;  // 2020-6-10 修改etka新建默认为普通订单
      this.createOrderType = 1;
      this.handleCreateDrawerChange(true);
    },
    // 点击处理过期订单
    async handleDealOverdueOrder() {
      let res = await dealOverdueOrder();
      if (res.resultCode == 200) {
        notifyAction('过期订单处理成功！', 'success');
      }
    },
    // 查询所有售前用户(锁定订单翻译用)
    async getDealerUser() {
      let res = await getDealerUser();
      let obj = {};
      res.data.map(item => {
        obj[item.userId] = item.employeeName;
      });
      this.userInfoData = obj;
    }
  }
};
</script>
